var pageCode = null, manuBatchCode = null, facilitiesCode = null, orgId = null;
var facIsNotNull = false;
var pageSet = {};
var EqCode = null;
var sgdText = "随工单";

$(function() {
	pageCode = request("code");
	orgId = request("orgId");
	manuBatchCode = request("manuBatchCode");
	facilitiesCode = request("facilitiesCode");
	if(manuBatchCode){
		$("#code").val(manuBatchCode);
		searchBatchInfo(manuBatchCode);
	}
	$("#code").focus();
	$("#code").keyup(function(e) {
		if(e.which == 13) {
			searchBatchInfo(this.value);
		}
	});
	//单晶车间
	if("13B5922D3A7F4B988DADDA9C0A963BDE" === orgId){
		sgdText = "工单";
		$("#sgdLabel").text("工单号:");
		$("#code").attr("placeholder", "请扫描工单编码");
		$("#codeInfo").attr("placeholder", "工单信息");
	}
	
	if (!pageCode) {
		alert("未搜索到传入的页面编码，请联系管理员！");
		return;
	}
	//多晶车间 投炉显示测棒等
	if("D9048326F1D9475A9E3AFC9B57A9E821" === orgId && pageCode === "WH_DUO_LLTL"){
		$("#testBar").show();
		$("#barResidue").show();
	}
	//多晶熔化工序显示 坩埚底厚，棒上端剩余 等信息
	if("D9048326F1D9475A9E3AFC9B57A9E821" === orgId && pageCode === "WH_DUO_RH"){
		$("#rhInfo").show();
	}
	//单晶 拉料投炉
	if("13B5922D3A7F4B988DADDA9C0A963BDE" === orgId && pageCode === "WH_DUO_LLTL"){
		$.post(host + "materialIn/getVehicleList", {
			routeNo: "30"
		}, function(res) {
			if(res.result){
				$.each(res.vehicleList, function(i, v) {
					var opt = '<option value="'+ v.EMES_FACILITIES_ID +'" data-mbcode="'+ v.MBCODE +'"'
						+ ' data-mbid="'+ v.MBID +'">'+ v.CODE +'</option>';
					$("#vehicle").append(opt);
				});
				layui.use("form", function(){
					var form = layui.form;
					form.on('select(vehicle)', function(data) {
						var mbCode = $("#vehicle option:selected").attr("data-mbcode");
						searchBatchInfo(mbCode);
						batchId = $("#vehicle option:selected").attr("data-mbid");
					});
				});
			} else {
				alert(res.msg);
			}
		}, "json");
		$("#manuBatchDiv").hide();
		$("#vehicleDiv").show();
	}
	$.post(host + "manuBatch/getManuPageInfo", {code: pageCode}, function(res) {
		if (res.result) {
			if (res.joinFac == "Y") {
				$("#facInput").show();
				$("#facInputInfo").show();
				
				facIsNotNull = true;
				if(facilitiesCode){
					$("#facCode").val(facilitiesCode);
					getMaterialInfo(facilitiesCode);
				}
				$("#facCode").keypress(function(e) {
					if(e.which == 13) {
						getMaterialInfo(this.value);
					}
				});
			}
			//单晶车间
			if(res.adOrgId === "13B5922D3A7F4B988DADDA9C0A963BDE") {
				//引晶工序显示 回熔按钮
				if(res.EMES_PROCESS_ID === "9217251E8CDF48CEB267CF17BBCC98CD"){
					vm.reworkText = "回熔";
					vm.showRework = true;
				}
				//放肩、转肩 工序 显示返工按钮
				if(res.EMES_PROCESS_ID === "1ED3728D01394907879C670B161CB3DA" 
					|| res.EMES_PROCESS_ID === "89D7517F8D7849F7A33EB2BF1AFAAE5A"){
					vm.showRework = true;
				}
			}
			
			pageSet = res;
			vm.Dc_Btn_List = res.Dc_Btn_List;
			//parent.clearInterval(parent.chgMenuInterval);
			//请求到后台，判定当前设备是否有在运行中的随工单
			$.post(host + "manuBatch/getManuBatchInfoByIp", {code: pageCode}, function(res) {
				if (res.result) {
					if (res.BATCHCODE) {
						$("#code").val(res.BATCHCODE);
						searchBatchInfo(res.BATCHCODE);
						/**
                        //获取自动跳转的请求信息
                        if(typeof(EventSource)!=="undefined"){
                            var source=new EventSource("../../manuBatch/isAutoJumpMenu?batchCode="+res.BATCHCODE+"&pageCode="+pageCode);
                            source.onmessage=function(event){
                                if(event.data !== ""){
                                    $.each($("button[onclick^='saveDCData']"),function(k,item){
                                        $(item).click();
                                    });
                                    var menuObj = JSON.parse(event.data);
                                    autoOpenMenu(menuObj.URL,menuObj.ICON,menuObj.NAME);
                                }
                            };
                        }else{
                            alert("浏览器不支持");
                        }
						 **/
					}
					if (res.CODE && facIsNotNull) {
						$("#facCode").val(res.CODE);
						getMaterialInfo(res.CODE);
					}
				}
			}, "json");
		} else {
			alert(res.msg);
		}
	}, "json");
});
var batchId = null, manuBatchInfo = null;
var facCode = null, facOriNumber = null;
function searchBatchInfo(code) {
	$.post(host + 'manuBatch/searchBatchInfo', {code: code, pageCode: pageCode}, function(res) {
		if (res.result) {
			manuBatchInfo = res;
			batchId = res.ID;
			//单晶车间  熔化工序首炉显示加料按钮
			if(res.AD_ORG_ID === "13B5922D3A7F4B988DADDA9C0A963BDE" 
					&& pageSet.EMES_PROCESS_ID === "DB3DC83397F544019F6E6EACA1D009BB"
					&& res.PUT_MATERIAL_COUNT === 1){
				vm.showAddMatBtn = true;
			}
			var html = "规格：" + nvl(res.CUT_METHOD, '') + 
					(res.TYPENAME ? "\r\n类型：" + res.TYPENAME : "") + 
					(res.PNAME ? "\r\n产品名称：" + res.PNAME : "") + 
					(res.PFNAME ? "\r\n配方名称：" + res.PFNAME + "(" + nvl(res.VERSION) + ")" : "") + 
					(res.IS_TEST == 'Y' ? "\r\n<span style='color: #f00;'>试验件</span>" : "") +
					(res.DESCRIPTION == 'Y' ? res.DESCRIPTION : "");
			$("#codeInfo").html(html);
			if(res.AD_ORG_ID === "13B5922D3A7F4B988DADDA9C0A963BDE"){
				html = "工单号：" + res.CODE +
					"\r\n坩埚尺寸：" + nvl(res.GG_NAME2) + "&nbsp;&nbsp;&nbsp;供应商：" + nvl(res.VENDOR_NAME) +
					"\r\n规格：" + nvl(res.CUT_METHOD, '') + 
					(res.TYPENAME ? "\r\n类型：" + res.TYPENAME : "");
				$("#vehicleInfo").html(html);
			}
			
			var rhInfo = '底板厚度：<span id="dbThickSpan" data-facid="'+ nvl(res.DIBAN_ID) +'">'
					+ '<input value="'+ nvl(res.DB_THICKNESS) +'"/><span id="dbThick">' + nvl(res.DB_THICKNESS) 
					+ '</span>mm <a id="upBtn">修改</a></span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
				'坩埚底厚：' + nvl(res.GG_DIHOU) + 'mm &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
				'棒上端剩余：' + nvl(res.RESIDUE_BAR) + 'mm';
			$("#rhInfoText").html(rhInfo);
			//修改底板厚度
			$("#upBtn").click(function() {
				var dbId = $("#dbThickSpan").attr("data-facid");
				if(dbId == ""){
					alert("底板不存在不能修改！");
					return;
				}
				if($("#dbThickSpan input:hidden").length > 0){	//当输入框隐藏时
					$("#dbThickSpan input").css('display', 'inline').focus();
					$("#dbThickSpan span").toggle();
					$(this).text("保存");
				} else {
					var dbThickness = $("#dbThickSpan input").val();
					if(!(dbThickness * 1 > 0)){
						alert('底板厚度不是一个正确的数字！');
						$("#dbThickSpan input").focus();
						return ;
					}
					$("#dbThickSpan input").hide();
					$("#dbThickSpan span").toggle();
					$("#dbThickSpan #dbThick").text($("#dbThickSpan input").val());
					$(this).text("修改");
					$.post(host + 'manuBatch/saveDbThick', {
						facId: dbId,
						dbThickness: dbThickness
					}, function(res) {
						if(!res.result){
							alert(res.msg);
						}
					}, 'json');
				}
			});
			$("#dbThickSpan input").keydown(function(e) {
				if(e.which === 13){
					$("#upBtn").click();
				}
			});

			//查询每个数据采集按钮的历史数据
			$.each(vm.Dc_Btn_List,function(t,v){
                getDataHistroy(v.EMES_DC_INPUT_DATA_ID);
			});
		} else {
			alert(res.msg);
		}
	}, "json");
}
function manuDataDc(pageId,type,url) {
	if(type == 'DC'){//数采
        $.post(host + 'manuFacilitiesDataController/getData', {pageId: pageId,batchId: batchId, processId: pageSet.EMES_PROCESS_ID}, function(res) {
            alert(res.msg);
            if (res.result) {
                getDataHistroy(pageId);
            }
        }, "json");
    }else if(type == 'DIALOG'){//对话框
		top.openUrl(url,"","80%","80%",window);
	}else if(type == 'FUNCTION'){
		 eval(url);
	}
}
//显示采集历史数据
function getDataHistroy(pageId) {
	$.post(host + 'manuFacilitiesDataController/getDataHistroy', {pageId:pageId,batchId: batchId, processId: pageSet.EMES_PROCESS_ID}, function(res) {
		if (res.result) {
			var containsKey = false;
			for(var i=0;i<vm.hisDataList.length;i++){
				var item = vm.hisDataList[i];
                if(item['PAGEID'] === res.key){
                    item['DATA'] = res.dataList;
                    containsKey = true;
                    break;
                }
			}
			if(!containsKey){
				var tmpDataMap = {};
				tmpDataMap['PAGEID'] = res.key;
				tmpDataMap['DATA'] = res.dataList;
				tmpDataMap['COLUMN'] = res.columnList;
				vm.hisDataList.push(tmpDataMap);
			}
			setTimeout(function () {
                $("#li"+pageId).click();
            },500);
		}
	}, "json");
}
function getMaterialInfo(code) {
	$.post(host + 'manuBatch/getFacilitiesInfo', {code: code}, function(res) {
		if (res.result) {
			facCode = code;
			facOriNumber = res.ORI_NUMBER;
			var text = nvl(res.NAME, '') + (res.ORI_NUMBER ? "\r\n型号：" + res.ORI_NUMBER : "");
			$("#facInfo").html(text);
		} else {
			alert(res.msg);
		}
	}, "json");
}
var subbool = false;
function submitData(rework) {
	//单晶投炉
	var vehicle = $("#vehicle").val();
	if("13B5922D3A7F4B988DADDA9C0A963BDE" === orgId && pageCode === "WH_DUO_LLTL"){
		if(!vehicle){
			alert("请选择载具！");
			$("#vehicle").focus();
			return;
		}
	}
	if (!batchId) {
		alert(sgdText + "号不规范！");
		return;
	}
	var fCode = $("#facCode").val();
	/*if(pageCode === "WH_DUO_LLTL"){
		EqCode = fCode;
	}*/
	if (facIsNotNull && !fCode) {
		alert("设备编码不能为空！");
		return;
	}
	var testBar = $("#barLength").val();
	var barResidue = $("#barResidue").val();
	//多晶投炉
	if("D9048326F1D9475A9E3AFC9B57A9E821" === orgId && pageCode === "WH_DUO_LLTL"){
		if($.trim(testBar) == "") {
			alert("[测棒信息]不能为空！");
			$("#barLength").focus();
			return;
		}
		if($.trim(barResidue) == "") {
			alert("[棒上端剩余]不能为空！");
			$("#barResidue").focus();
			return;
		}
		if(!(testBar * 1 >= 0)){
			alert("[测棒信息]请填写大于等于0的数字！");
			$("#barLength").focus();
			return;
		}
		if(!(barResidue * 1 >= 0)){
			alert("[棒上端剩余]请填写大于等于0的数字！");
			$("#barResidue").focus();
			return;
		}
	}
	//单晶投炉
	if("13B5922D3A7F4B988DADDA9C0A963BDE" === orgId && pageCode === "WH_DUO_LLTL"){
		if(manuBatchInfo.CUT_METHOD === "GB120" && facOriNumber && facOriNumber.includes("90")){
			alert("GB120规格的工单不能投入90型号的炉台！");
			return;
		}
	}
	if (subbool) {
		return;
	}
	subbool = true;
	$.post(host + 'manuBatch/saveManuProcess', 
		{id: batchId, facCode: fCode, description: $("#description").val(), code: pageCode, isRework: rework,
			testBar: testBar, barResidue: barResidue, vehicle: vehicle},
		function(res) {
			if(res.result){
				//多晶车间 投炉显示母锭编码等
				if("D9048326F1D9475A9E3AFC9B57A9E821" === orgId && pageCode === "WH_DUO_LLTL"){
					$("#mainProductCodeDiv").show();
					$.post(host + 'manuBatch/searchMainProductCodeByBatchId',{id:batchId},function(res){
						$("#oldMainProductCode").html(res.CODE);
						$("#newMainProductCode").val(res.CODE);
					},"json");
				}
			}
			subbool = false;
			if (res.msg == "rework") {
				if (window.confirm("“" + pageSet.NAME + "” 工序之前已执行，是否再次执行“" + pageSet.NAME + "”工序？")) {
					submitData('true');
				}
				return;
			}
			else if(res.resultss == "false"){

				if(confirm("该工序开工前需点检，是否前往？")){
					//window.location.href = "http://127.0.0.1:28080/pda/mes/equipment/equipmentInspection.html";
					var x = window.screen.height;
					var y = window.screen.width;
					var h = 500;
					var w = 800;
					var model = "title=word,resizable=yes,scrollbars=yes,height=" + h + ",width=" + w + ",directories = no ,status=no,toolbar=no,menubar=no,location=no,top=" + (x-h)/2 + ",left=" + (y-w)/2;
					var url = "";
					url = "../../mes/equipment/equipmentInspection.html";//弹出窗口的页面内容
					var oOpen = window.open(url,"adviceDetail",model);
					//oOpen.focus();
				}
			}else{
				alert(res.msg);
			}
			if (res.result && res.IS_REFRESH == 'Y') {
				window.location.reload();
			}
	}, "json");
}

/*function showEQ(obj){
	var x = window.screen.height;
	var y = window.screen.width;
	var h = 500;
	var w = 800;
	var model = "title=word,resizable=yes,scrollbars=yes,height=" + h + ",width=" + w + ",directories = no ,status=no,toolbar=no,menubar=no,location=no,top=" + (x-h)/2 + ",left=" + (y-w)/2;
	var url = "";
	
	url = "http://127.0.0.1:28080/pda/mes/equipment/equipmentInspection.html";//弹出窗口的页面内容
	var oOpen = window.open(url,"adviceDetail",model);
	oOpen.focus();
}*/

function rework() {
	if (!batchId) {
		alert(sgdText + "号不规范！");
		return;
	}
	$("#reworkDialog").dialog({
		title: "返工",
		autoOpen: true,
		height: 320,
	    width: 350,
	    modal: true,
	    buttons: {
	    	"保存": function() {
				var reworkReason = $("#reworkReason").val();
				if(reworkReason == ""){
					alert("请输入返工原因！");
					return;
				}
				if (subbool) {
					return;
				}
				subbool = true;
				$.post(host + 'manuBatch/rework', 
				{id: batchId, code: pageCode, reworkReason: reworkReason},
				function(res) {
					subbool = false;
					alert(res.msg);
					if (res.result && res.IS_REFRESH == 'Y') {
						window.location.reload();
					}
				}, "json");
			},
	    	"取消": function() {
				$(this).dialog("close");
			}
	    }
	});
}
//加料
function addMaterial() {
	top.openUrl(host + "mes/manu/addMaterial.jsp?code=" + $("#code").val(), "加料", "80%", "80%", window);
}

function refresh() {
	window.location.reload();
}
//保存数采的数据
function saveDCData(pageId){
	var data = null;
	$.each(vm.hisDataList,function(i,v){
		if(v.PAGEID == pageId){
            data = v.DATA;
		}
	});
	if(data == null){
        alert("数据为空，请检查！");
        return;
	}
    $.post(host + 'manuBatch/saveDCData',
        {pageId:pageId,data:JSON.stringify(data)},
        function(res) {
    	alert(res.msg);
	}, "json");
}

//自动跳转菜单
function autoOpenMenu(url,icon,name){
    $("#mainFrame", window.parent.document).attr("src",url);
    $("#mainTitleImg", window.parent.document).attr("src",icon);
    $("#mainTitleSpan", window.parent.document).html(name);
}

//自定义函数
/**
 *
 * @param pageId  当前按钮的ID
 * @param title   窗口标题
 * @param routeNo  跳转到的工序号
 * @param isFresh 是否刷新当前页面
 * @param length 原因限制的字符长度
 * @param desc  默认显示的原因提示语
 */
function customFn(pageId,title,routeNo,isFresh,length,desc) {
	if (!batchId) {
		alert(sgdText + "号不规范！");
		return;
	}
	desc ? $("#reworkReason").attr("placeholder",desc) : '';
	$("#reworkDialog").dialog({
		title: title,
		autoOpen: true,
		height: 320,
		width: 350,
		modal: true,
		buttons: {
			"保存": function() {
				var reworkReason = $("#reworkReason").val();
				if(reworkReason == ""){
					alert("请输入"+title+"原因！");
					return;
				}
				if(length && reworkReason.length > length){
				   alert("原因只允许输入"+length+"个字符！");
				   return;
				}
				if (subbool) {
					return;
				}
				subbool = true;
				$.post(host + 'manuBatch/customFn',
					{id: batchId, code: pageCode, reworkReason: reworkReason,routeNo:routeNo,pageId:pageId},
					function(res) {
						subbool = false;
						alert(res.msg);
						if (res.result && isFresh) {
							window.location.reload();
						}
					}, "json");
			},
			"取消": function() {
				$(this).dialog("close");
			}
		}
	});
}

/**
 * 删除数采数据
 * @param id
 */
function delManuData(id){
	$.post(host + 'manuBatch/delManuData',
		{id: id},
		function(res) {
			if (res.result) {
				searchBatchInfo($("#code").val());
			}
		}, "json");
}


//修改母锭编码
function modifyMainProductCode(){
	var modifyText = $("#modifyMainProductCode").html();
	if("编辑" === modifyText){
		$("#oldMainProductCode").hide();
		$("#newMainProductCode").attr("type","text");
		$("#modifyMainProductCode").html("保存");
		$("#cancelModify").show();
	}else{
		var oldMainProductCode = $("#oldMainProductCode").text();
		var newMainProductCode = $("#newMainProductCode").val();
		$.post(host + 'billetInstorage/modifyMainProductCode', {
			oldMainProductCode:oldMainProductCode
			,newMainProductCode:newMainProductCode
		}, function(res) {
			alert(res.msg);
			if(res.result){
				$("#oldMainProductCode").html($("#newMainProductCode").val());
				$("#oldMainProductCode").show();
				$("#newMainProductCode").attr("type","hidden");
				$("#modifyMainProductCode").html("编辑");
				$("#cancelModify").hide();
			}
		}, "json");
	}
}
//取消母锭编码编辑按钮
function cancelModify(){
	$("#oldMainProductCode").show();
	$("#newMainProductCode").attr("type","hidden");
	$("#modifyMainProductCode").html("编辑");
	$("#cancelModify").hide();
}